package com.city.msmservice.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.city.msmservice.service.MsnService;
import com.city.msmservice.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * Created with IntelliJ IDEA.
 * User: Cheng
 * Date: 2020/9/26
 * Time: 17:26
 * Description: No Description
 */
@Service
public class MsnServiceImpl implements MsnService {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public Boolean getCode(String phone) {
        //自己生成四位或六位的验证码
        String code= RandomUtil.getSixBitRandom();
        Map<String,Object> map=new HashMap<>();
        map.put("code",code);
        if (StringUtils.isEmpty(phone)) {return false;}
        DefaultProfile profile=DefaultProfile.getProfile("default","LTAI4GFE5PsLWjG5B1ZXo2T7","8agZ6EkIseW3cfM12Jn4PTIpWPAZMi");
        IAcsClient client=new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        //request.setProtocol(ProtocolType.HTTPS);
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");

        //设置发送相关的参数
        request.putQueryParameter("PhoneNumbers",phone); //手机号
        request.putQueryParameter("SignName","Hello在线教育"); //申请阿里云 签名名称
        request.putQueryParameter("TemplateCode","SMS_203676879"); //申请阿里云 模板code
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(map)); //验证码数据，转换json数据传递

        try {
            //最终发送
            CommonResponse response = client.getCommonResponse(request);
            boolean success = response.getHttpResponse().isSuccess();
            if (success){
                //短信发送成功，将验证码存进redis定时5分钟，验证的时候从redis拿出来，对比验证码是否正确，如果超过五分钟则没有，则错误
                //设置有效时间
                redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            }
            return success;
        }catch(Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
